package com.ljy.my_study.lintcode.获取子字符串在字符串中索引;
/** 
* @author James
* @date 2018年4月19日 
*/
public class SubStringMain {
	public static void main(String[] args) {
		System.out.println(subString2("abcde","e"));
	}
	
	public static int subString(String haystack, String needle) {
		if(haystack==null||needle==null) {
			return -1;
		}
		char[] array=haystack.toCharArray();
		char[] subArray=needle.toCharArray();
		if(array.length<subArray.length) {
			return -1;
		}
		if(subArray.length==0) {
			return 0;
		}
		int num=0;
		for(int i=0;i<=array.length-subArray.length;i++) {
			for(int j=0;j<subArray.length;j++) {
				if(array[i+num]==subArray[j]) {
					if(j==subArray.length-1) {
						return i+num-subArray.length+1;
					}
					num++;
				}else {
					num=0;
					break;
				}
			}
			
		}
		return -1;
	}
	public static int subString2(String haystack, String needle) {
		if(haystack==null||needle==null) return -1;
		int sourceLen=haystack.length();
		int targetLen=needle.length();
		if(sourceLen<targetLen) return -1;
		if(targetLen==0) return 0;
		for(int i=0;i<sourceLen-targetLen+1;i++) {
			String s=haystack.substring(i, i+targetLen);
			if(needle.equals(s)) {
				return i;
			}
		}
		return -1;
	}
}
